//添加习惯的接口
const router = require('koa-router')()
const userService = require('../controllers/mySqlControll.js')
const utils = require('../config/utils.js')



router.prefix('/habit')

//根据分类查找对应的习惯列表
// router.post('/findHabitByType', async (ctx, next) => {
//   //console.log(ctx.request.body);
//   const { habit_lable } = ctx.request.body
//   //去habit库中查找所有的类型为habit_label的习惯
//   try {
//     const result = await userService.findHabitByType(habit_lable)
//     //console.log(result);
//     ctx.body = {
//       code: '80000',
//       data: result,
//       msg: '查找成功'
//     }
//   } catch (error) {
//     ctx.body = {
//       code: '80002',
//       data: error,
//       msg: '服务器异常'
//     }
//   }

// })

//查找全部的习惯列表
router.post('/findAllHabit', async (ctx, next) => {
  //console.log(ctx.request.body);
  const data = ctx.request.body
  //去habit库中查找所有的类型为habit_label的习惯
  try {
    const result = await userService.findAllHabit(data)
    //console.log(result);
    ctx.body = {
      code: '80000',
      data: result,
      msg: '查找成功'
    }
  } catch (error) {
    ctx.body = {
      code: '80002',
      data: error,
      msg: '服务器异常'
    }
  }

})

// 添加习惯
router.post('/publish', async (ctx, next) => {
  const {
    title,
    habit_label,
    color,
    icon_class,
  } = ctx.request.body

  const add_time = utils.formateDate(new Date())

  try {
    const result = await userService.addHabit([title, habit_label, color, icon_class, add_time])
    console.log(result);
    if (result.affectedRows !== 0) {
      ctx.body = {
        code: '80000',
        data: 'ok',
        msg: '添加成功'
      }
    } else {
      ctx.body = {
        code: '80004',
        data: 'error',
        msg: '添加失败'
      }
    }
  } catch (error) {
    ctx.body = {
      code: '80002',
      data: error,
      msg: '服务器异常'
    }
  }
})

// 删除习惯
router.post('/deleteHabit', async (ctx, next) => {
  const { id } = ctx.request.body
  try {
    const result = await userService.deleteHabit(id)
    console.log(result);
    if (result.affectedRows !== 0) {
      ctx.body = {
        code: '80000',
        data: 'ok',
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        code: '80004',
        data: 'error',
        msg: '删除失败'
      }
    }
  } catch (error) {
    ctx.body = {
      code: '80002',
      data: error,
      msg: '服务器异常'
    }
  }
})

module.exports = router
